
package com.epam.android.training.day6.task2;

import com.epam.android.training.day6.task2.Contacts.Names;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

/**
 * Main activity shows list of contacts from database. Initiates new contact
 * creation.
 * 
 * @author Anton Novikau
 */
public class ContactsList extends Activity {

  private static final String[] PROJECTION = {
      Names._ID, Names.FIRST_NAME, Names.LAST_NAME
  };

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ListView contactsContainer = (ListView) findViewById(R.id.contacts);
    populateContacts(contactsContainer);

    addCreateNewButtonAction();
  }

  /**
   * Populates contacts list view with data from {@link Contacts.Names} table.
   * 
   * @param contactsContainer {@link ListView} to populate with data from
   *          backend
   */
  private void populateContacts(ListView contactsContainer) {
    Cursor resultSet = managedQuery(Names.CONTENT_URI, PROJECTION, null, null, null);
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_item, resultSet,
        new String[] {
            Names.FIRST_NAME, Names.LAST_NAME
        }, new int[] {
            R.id.first_name_item, R.id.last_name_item
        });
    contactsContainer.setAdapter(adapter);
  }

  /**
   * Adds action to "create new contact" button. Must start {@link ContactAdder}
   * activity.
   */
  private void addCreateNewButtonAction() {
    Button addNewButton = (Button) findViewById(R.id.add_new);
    addNewButton.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        startActivity(new Intent(Intent.ACTION_INSERT, Names.CONTENT_URI));
      }
    });
  }
}
